import Koa from 'koa';
import websocket from 'koa-easy-ws';
import { Server } from '@hocuspocus/server';
import { Logger } from '@hocuspocus/extension-logger';
import { Database } from '@hocuspocus/extension-database';
import { TiptapTransformer } from '@hocuspocus/transformer';

const server = Server.configure({
	onConnect: async (data) => {
		console.log('New connection');
	},
	onDisconnect: async (data) => {
		console.log('Disconnected');
	},
	onStoreDocument: async (data) => {
		const json = TiptapTransformer.fromYdoc(data.document, 'default');
		console.log('Document stored .... ', data.documentName, json);
	},
	onLoadDocument: async (data) => {
		console.log('Document loaded');
	},
	extensions: [
		new Database({
			store: async ({ documentName, state }) => {
				console.log('Store db ... ', documentName, state);
			}
		})
	]
});

const app = new Koa();

app.use(websocket());

app.use(async (ctx, next) => {
	const ws = await ctx.ws();

	server.handleConnection(
		ws,
		ctx.request,
		// additional data (optional)
		{
			user_id: 1234
		}
	);
});

app.listen(1234);
